// Module/ttsModule.js
// 兼容版 TTS 模块，支持低版本 Auto.js/AutoX.js

let tts;
let isReady = false;
let utteranceListener = null; // 保存监听器引用

exports.initTTS = function(ctx, callback) {
    try {
        let TextToSpeech = android.speech.tts.TextToSpeech;

        tts = new TextToSpeech(ctx, new TextToSpeech.OnInitListener({
            onInit: function(status) {
                if (status === TextToSpeech.ERROR) {
                    console.error("TTS 初始化失败：引擎错误");
                    isReady = false;
                    if (typeof callback === 'function') {
                        callback(false);
                    }
                    return;
                }

                // 设置语言为中文
                let result = tts.setLanguage(java.util.Locale.SIMPLIFIED_CHINESE);
                if (result === TextToSpeech.LANG_MISSING_DATA ||
                    result === TextToSpeech.LANG_NOT_SUPPORTED) {
                    console.warn("⚠️ 中文不支持，尝试英文");
                    tts.setLanguage(java.util.Locale.US);
                }

                // ✅ 手动创建并设置监听器（不再尝试获取）
                utteranceListener = new android.speech.tts.UtteranceProgressListener({
                    onStart: function(utteranceId) {
                        console.log("[TTS] 开始播报: " + utteranceId);
                    },
                    onDone: function(utteranceId) {
                        console.log("[TTS] 播报完成: " + utteranceId);
                        if (typeof this.onComplete === 'function') {
                            this.onComplete();
                        }
                    },
                    onError: function(utteranceId) {
                        console.error("[TTS] 播报出错: " + utteranceId);
                        if (typeof this.onComplete === 'function') {
                            this.onComplete(); // 出错也继续队列
                        }
                    }
                });

                tts.setOnUtteranceProgressListener(utteranceListener);

                isReady = true;
                console.log("TTS 初始化成功");
                if (typeof callback === 'function') {
                    callback(true);
                }
            }
        }));

    } catch (e) {
        console.error("初始化TTS异常: " + e);
        if (typeof callback === 'function') {
            callback(false);
        }
    }
};

// 设置语速 (0.5 ~ 2.0)
exports.setSpeechRate = function(rate) {
    if (!isReady || !tts) return;
    let r = Math.max(0.5, Math.min(2.0, rate));
    tts.setSpeechRate(r);
};

// 朗读文本，并在完成后调用回调
exports.speakText = function(text, onComplete) {
    if (!isReady || !tts) {
        console.warn("TTS 未准备好，跳过: " + text);
        if (typeof onComplete === 'function') {
            setTimeout(onComplete, 100);
        }
        return;
    }

    try {
        let utteranceId = "utt_" + Date.now();

        // ✅ 将 onComplete 绑定到监听器的作用域中
        if (utteranceListener && typeof onComplete === 'function') {
            utteranceListener.onComplete = onComplete;
        }

        let bundle = new android.os.Bundle();
        bundle.putString(
            android.speech.tts.TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
            utteranceId
        );

        let result = tts.speak(
            text,
            android.speech.tts.TextToSpeech.QUEUE_ADD,
            bundle,
            utteranceId
        );

        if (result === android.speech.tts.TextToSpeech.ERROR) {
            console.error("❌ 播报失败: " + text);
            if (typeof onComplete === 'function') {
                onComplete(); // 失败也触发回调，避免卡住队列
            }
        } else {
            console.log("📢 已加入播报队列: " + text);
        }
    } catch (e) {
        console.error("播报异常: " + e);
        if (typeof onComplete === 'function') {
            onComplete();
        }
    }
};

// 可选：关闭资源
exports.shutdownTTS = function() {
    if (tts) {
        tts.stop();
        tts.shutdown();
        isReady = false;
        utteranceListener = null;
        console.log("TTS 已关闭");
    }
};